Function Post-CosmData {
<#       
.SYNOPSIS
	Loads a set of datapoints (timestamp/vaue) to a specified feed/datastream in Cosm
.DESCRIPTION
	A supplied xml object is wrapped in an eeml tag and sent to Cosm for processing
.PARAMETER $pbDatapoints
	An XML object identifying the feedid, datastreamid and a set of datapoints to be created or updated
	This is the format of the input xml file
	  <environment id="$feedid">
		<data id="$DataStreamId">
		  <datapoints>
			<value at="2010-05-20T11:01:43Z">294</value>
			<value at="2010-05-20T11:01:44Z">295</value>
			...
			<value at="2010-05-20T11:01:46Z">297</value>
		  </datapoints>
		</data>
	  </environment>
	  Other nodes or attributes if present will be ignored as long s they do not change the structure. 
	  The format is largely the same as the output from a history query on a data stream once the enclosing eeml tag is removed
.EXAMPLE
	$String = Post-CosmData  @{feed="40873"; datastreams="1,2,6"; apikey="1234567890"; interval="300"; timezone="Melbourne"} $FromTimestamp 
	# returns all data in a script variable
.EXAMPLE
	$Spec=@{}
	$Spec.feed="40873"
	$Spec["datastreams"]="1,2,6"
	$spec.apikey="1234567890"
	$spec.interval=300
	$spec.timezone="+11"
	Post-CosmData $spec $FromTimestamp | Next_Function # passes data in Powershell pipeline
.NOTES 1
.NOTES 2

<eeml xmlns="http://www.eeml.org/xsd/0.5.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="0.5.1" xsi:schemaLocation="http://www.eeml.org/xsd/0.5.1 http://www.eeml.org/xsd/0.5.1/0.5.1.xsd">
</eeml>
#>  

	param(
		[Parameter(Mandatory=$true,Position=0)]$pbDepositSTR
		,[Parameter(Mandatory=$true,Position=1)]$APIKey
	)
	Begin {
		Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started" 
		
		#------------------
		# Create Web Client 
		#------------------		
		pbWC = WebClient  -baseaddress "http://api.Cosm.com/v2/feeds/"
		$pbWC.Headers.Add("X-ApiKey",$APIKey)
		$pbQueryHT = new-object System.Collections.Specialized.NameValueCollection

	}
	Process {	Write-Verbose "$($MyInvocation.MyCommand.Name):: Process started"
		Try { # Post Cosm Data
			Try { #validate Input Data and obtain Cosm defaults
				if ($pbDepositSTR -is [string]){
					switch ($pbDepositSTR.substring(0,1)) {# if first char is '<', xml; '{', json; default csv
						'[' {#treat xml					
							$XMLData=[xml]$pbDepositSTR
							}	
						'{' {#treat as json
						}
						default {#treat as CSV
							#TODO:
						}
					}
				}
			
				elseif ($pbDepositSTR -is [xml]) {
					$XMLData=[xml]$pbDepositSTR
				}
				
				$pbFeedId=$XMLData.eeml.environment.GetAttribute("id")
				$pbDataStreamId=$XMLData.eeml.environment.data.GetAttribute("id")
				$pbFormat="xml"
				$pbUriSTR=[string]::Concat(  $pbFeedId, 	"/datastreams/", $pbDatastreamId, "/datapoints")       
				write-Host "Sending Cosm History datapoints to Feed $pbFeedId Datastream $pbDatastreamId"
				
				#----------------------------------
				# Cosm won't update any data if you send too much. Current limit =500 datapoints
				#TODO: Check whether OK using measure-object? For now rely on calling routine
			} #validate Input Data and obtain Cosm defaults
			catch {	#validate Input Data and obtain Cosm defaults
			}
			Try { # Setup Web client for sending data  
				#------------------------------
				# Set Query parameters
				#------------------------
				$pbQueryHT.clear() # empty the query string
				$pbWC.QueryString = $pbQueryHT 	# Attach QueryString to the WebClient.
				#write-Host $pbQueryHT[$pbQueryHT.keys]
				write-debug "pbUriSTR=$pbWC.baseaddress $pbUriSTR"
			} # Setup Web client for sending data
			catch {  # Report Web client setup Error
				Throw "$($MyInvocation.MyCommand.Name):: Unknown Problem "
			}  # Report Web client setup Error
			try { # Upload Cosm Data
				# send all datapoints as a single string
				$pbResponseSTR = $pbWC.UploadString($pbUriSTR, "POST", $XMLData.InnerXml) 
				$pbResponseHeaders=$pbWC.ResponseHeaders
			} # Upload Cosm Data
			catch { # Report Upload Cosm Data Error
					Throw "$($MyInvocation.MyCommand.Name):: Web Client Setup Error $_ "
			} # Report Upload Cosm Data Error
			finally {
				$pbResponseSTR
			}
		} # Get Cosm Data
		Catch { # Report Post Cosm Data Error with StackTrace
			write-Host "problem posting data to Cosm $_ `n $StackTrace"
		} # Report Post Cosm Data Error with StackTrace
	}
	End {
		Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"
		#Return $pbExtractedSTR
		$pbWC.dispose
	} 
}

